/**
 * 
 */
package org.statewalker.parser.wiki.tokenizer.block;

import org.statewalker.tokenizer.AbstractTokenizer;
import org.statewalker.tokenizer.CharStream;
import org.statewalker.tokenizer.StreamToken;
import org.statewalker.tokenizer.CharStream.Marker;
import org.statewalker.tokenizer.CharStream.Pointer;
import org.statewalker.tokenizer.base.NewLineTokenizer;

public class HeaderEndTokenizer extends AbstractTokenizer {

    public HeaderEndTokenizer(String key) {
        super(key);
    }

    protected boolean checkChar(char ch) {
        return ch == '=';
    }

    private boolean isSpace(char ch) {
        return ch == ' ' || ch == '\t';
    }

    public StreamToken read(CharStream stream) {
        // If we are at the end of the stream then it is definitely the end of
        // the header
        if (stream.isTerminated()) {
            Pointer ptr = stream.getPointer();
            StreamToken result = newToken(ptr, ptr, "");
            result.setOpen(false);
            result.setClose(true);
            return result;
        }

        // Now we have to check if the line ends with the "[=]*\n(\s+)" pattern
        StreamToken result = null;
        Marker marker = stream.markPosition();
        try {
            boolean ok = false;
            // [=]*
            while (checkChar(stream.getChar())) {
                ok = !stream.incPos();
            }
            if (!ok) {
                // Skip all white spaces before the end of the line
                while (isSpace(stream.getChar()) && stream.incPos()) {
                }
                // Check that we are at the end of the line
                ok = NewLineTokenizer.readNewLine(stream) != null
                    || stream.isTerminated();
            }
            if (ok) {
                result = newToken(stream, marker);
                result.setOpen(false);
                result.setClose(true);
            }
            return result;
        } finally {
            marker.close(result == null);
        }
    }

}